package com.zyw.concurrent.lock;

import java.util.LinkedList;
import java.util.List;

/**
 * 系统退出命令
 * <p/>
 *
 * @author zhangyw
 * @date 16/3/31 21:40 14:22
 */
public class SystemExitListener {

    private static boolean over = false;

    private static List<ExitHandler> exitHandlers = new LinkedList<ExitHandler>();

    static {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (exitHandlers) {
                    if (isOver()) {
                        for (ExitHandler exitHandler : exitHandlers) {
                            exitHandler.run();
                        }
                    }
                }
            }
        });
        t.setDaemon(false);
        t.start();
    }

    public static boolean isOver() {
        return over;
    }

    public static void addTerminateListener(ExitHandler exitHandler) {
        synchronized (exitHandlers) {
            if (isOver()) {
                return;
            }
            exitHandlers.add(exitHandler);
        }
    }

    public static void exit() {
        over = true;
    }
}
